#!/usr/bin/env python
# -*- coding: utf-8 -*-
#code:utf-8
#
# Copyright(C) 2011 SupDo.com
# Licensed under the GUN License, Version 3.0 (the "License");
# 
# File:        forms
# Author:      KuKei
# Create Date: 2011-04-18
# Description: 视图目录
# Modify Date: 2011-04-18

from django.utils import simplejson
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect as HRedirect
from sd.cms.lib.utility import *
from sd.cms.lib import Params, Result, SDMemCache
from sd.cms.lib.decorator import cacheBase, powerLevel
from sd.cms.lib.template import Template
from sd.cms.lib.utility import nvl, QSetToDict, trimRight, renderToResponse
from sd.cms.models.paramModel import Catalog, Column, Param ,Global, GlobalParam
from django.forms.models import model_to_dict
import string, datetime,time, random

#表单基类
class BaseView():
    #发送到页面做渲染用的数据
    viewData = {}
    #配置的基本参数
    params = Params()
    tpl = Template()
    #页面来的请求信息
    request = None
    #即将发送到客户端的数据
    rtor = None
    result = Result()
    mc = None
    globalinfo = None
    globalparam = None
    isAdminView = None
    starttime = None
    
    #权限验证字典
    power = {'isLogin':False,'user':None}
    
    def __init__(self, request):
        self.request = request
        self.starttime = time.time()
        self.isAdminView = False
        self.mc = SDMemCache()
        self.power = self.request.session[self.params.POWER] \
                    if self.request.session.has_key(self.params.POWER) else self.power
        self.globalinfo, self.globalparam = self.getGlobal()
        self.initSite()

    class Meta:
        #Meta中的abstract属性表明此类为抽象类，可以做基类；
        abstract = True
    
    #网站基本参数初始化
    def initSite(self):
        #catalogs = self.mc.get(self.params.CATALOGS)
        site = {
                self.params.PARAM: self.params ,
                self.params.THEME: self.globalinfo.theme if self.globalinfo.theme else 'default',
                self.params.POWER: self.power,
                self.params.CATALOGS: self.getCatalog()[0],
                self.params.GLOBAL: self.globalinfo,
                self.params.GLOBALPARAM: self.globalparam,
                }
        self.viewData['site'] = site
        
    @cacheBase(key=params.CATALOGS)
    def getCatalog(self):
        catalogList = list(Catalog.objects.filter(isdisplay=1).order_by('orderby'));
        columnDict = QSetToDict(list(Column.objects.all()))
        paramDict = QSetToDict(list(Param.objects.filter(kind=1)))
        retList = []
        retDict, retDict2 = {}, {}
        for e1 in catalogList:
            retDict[e1.value] = e1
            retDict2[e1.id] = e1
            if e1.level == 10:
                column = columnDict[e1.column_id]
                column.model = paramDict[column.model_id]
                e1.column = column
                retList.append(e1)
                for e2 in catalogList:
                    if e2.level == 20 and e2.parent == e1.id:
                        column = columnDict[e2.column_id]
                        column.model = paramDict[column.model_id]
                        e2.column = column
                        retList.append(e2)
        return [retList, retDict, retDict2, columnDict, paramDict]
    
    @cacheBase(key=params.GLOBAL)
    def getGlobal(self):
        globalModel = list(Global.objects.all())
        globalinfo = globalModel[0] if len(globalModel)>0 else Global()
        pList = list(GlobalParam.objects.filter(autoload=True).order_by('kind','orderby'))
        globalParam = {}
        for p in pList:
            if not globalParam.has_key(p.kind):
                globalParam[p.kind] = {}
            globalParam[p.kind][p.code] = p.value
        print globalParam
        return globalinfo, globalParam
    
    def getLocationLists(self, catalog, nowpath=None):
        retLists = []
        if not catalog:
            return retLists
        elif catalog.parent > -1:
            retLists.append(Catalog.objects.get(id=catalog.parent))
            retLists.append(catalog)
        elif catalog.parent == -1:
            retLists.append(catalog)   
        if nowpath:
            retLists.append({'name':nowpath})
        return retLists

    #根据自己的函数名字符串调用函数
    def action(self, **args):
        #先做权限判断
        try:
            if not apply(self.isPowered, (), args):
                self.result = Result(False,'您没有权限执行此次操作！','','/login.html',3)
                return self.toSkip()
                
            if args.has_key('action') and args['action']:
                if not args.has_key('suffix') or args['suffix'] == "do":
                    return apply(eval('self.'+args['action']), (), args)
                elif args['suffix'] == "html":
                    return apply(eval('self.'+args['action']+"View"), (), args)
                else:
                    return None
            else:
                return apply(eval('self.view'), (), args)
        except Exception,ex:
            self.result.flag = False
            self.result.msg = str(ex.args)
            return self.toSkip()
    
    def isPowered(self, **args):
        isPower = False
        #管理模块必须管理员级别以上的操作员才有权进入
        if self.isAdminView:
            if self.request.session.has_key(self.params.POWER):
                powerSeesion = self.request.session[self.params.POWER]
                if powerSeesion['isLogin'] and powerSeesion['user'].power >= self.params.ADMINISTRATOR:
                    isPower = True
        else:
            isPower = True
        return isPower
    
    def preRender(self):
        self.viewData['result'] = self.result
        
    #重写view输出函数，使用基类中的数据
    def render(self, tplUrl, theme=None):
        if not theme:
            theme = self.globalinfo.theme
        self.preRender()
        self.rtor = renderToResponse(tplUrl, self.viewData, theme)
        #计算页面生成所用时间
        updateStr = self.rtor.content[-112:].replace('#updateTime#', datetime.datetime.now().strftime('%H:%M:%S'))
        updateStr = updateStr.replace('#seconds#', trimRight('%.6f'%(time.time()-self.starttime)))
        self.rtor.content = self.rtor.content[:-112] + updateStr
        return self.rtor
    
    def render_json(self, result=None):
        if not result:
            result = self.result
        #tmpStr = simplejson.dumps(result.tojson())
        #print 'simplejson.dumps(result.tojson()):'+tmpStr
        return HttpResponse(simplejson.dumps(result.tojson()))
    
    def redirect(self, path):
        return HRedirect(path);
    
    def toSkip(self):
        if self.request.POST and self.request.POST.has_key('_retType') and self.request.POST['_retType'] == 'json':
            return self.render_json()
        else:
            self.result.sleep = toInt(self.request.GET['_sleep']) if self.request.GET and self.request.GET.has_key('_sleep') else self.result.sleep
            self.result.toUrl += '?_toUrl=%s' % (self.request.GET['_toUrl'] if self.request.GET and self.request.GET.has_key('_toUrl') else '/')
            #如果sleep是0则直接转到toUrl
            if self.result.sleep:
                return self.render('/snippet/skip.html')
            else:
                return self.redirect(self.result.toUrl)